import 'package:wu_you/data/db/db.dart';


///存储转账历史user
class TransferUserDao {
  factory TransferUserDao() => _getInstance();
  static TransferUserDao _instance;

  TransferUserDao._internal();

  static TransferUserDao _getInstance() {
    if (_instance == null) {
      _instance = TransferUserDao._internal();
    }
    return _instance;
  }

  static const _TABLE_NAME = "transfer_user";

  ///查询所有
  Future<List<String>> getAll(String mobile) async {
    var db = await DatabaseHelper().db();
    List<Map<String, Object>> result = await db.query(
      _TABLE_NAME,
      columns: ["user_name"],
      where: 'mobile = ?',
      whereArgs: [mobile],
      orderBy: 'transfer_count desc',
    );
    return result.map((e) => e['user_name'] as String).toList();
  }

  ///插入新数据
  ///如果存在则更新转账次数
  Future<int> insert(String mobile, String username) async {
    var db = await DatabaseHelper().db();
    int result = 0;
    int count = await db.rawUpdate("update transfer_user set transfer_count = transfer_count + 1 where mobile = ? and user_name = ?", [mobile, username]);
    result = count;
    if (count == 0) {
      int res = await db.insert(_TABLE_NAME, {"mobile": mobile, "user_name": username, "transfer_count": 1});
      result = res;
    }
    return result;
  }

  ///删除
  Future<int> delete(String mobile, String username) async {
    var db = await DatabaseHelper().db();
    int result = 0;
    result = await db.delete(_TABLE_NAME, where: 'user_name = ? and mobile = ?', whereArgs: [username, mobile]);
    return result;
  }

  ///删除所有
  Future<int> deleteAll(String mobile) async {
    var db = await DatabaseHelper().db();
    int result = 0;
    result = await db.delete(_TABLE_NAME, where: 'mobile = ?', whereArgs: [mobile]);
    return result;
  }
}
